﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace CommonLibraries.DeviceLibrary.Controls
{
    public partial class PortWatcher : UserControl
    {
        System.IO.Ports.SerialPort m_SerialPort = null;
        GPS m_GPS;

        public PortWatcher()
        {
            InitializeComponent();
            m_SerialPort = new System.IO.Ports.SerialPort();
            m_SerialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(m_SerialPort_DataReceived);
            //m_SerialPort.PortName = "COM2";
            m_SerialPort.BaudRate = 115200;
            m_SerialPort.Open();

            this.textBoxOutput.Text = m_SerialPort.PortName + " Opened.";

            //m_GPS = new GPS();
        }

        void m_SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            this.BeginInvoke(new ThreadDelegate(this.ThreadInvoke), m_SerialPort.ReadExisting());
        }

        private delegate void ThreadDelegate(string variable);
        void ThreadInvoke(string threadingString)
        {
            this.textBoxOutput.Text = threadingString + this.textBoxOutput.Text;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.labelTime.Text = DateTime.Now.ToString();
        }

        private void buttonPower_Click(object sender, EventArgs e)
        {
            m_GPS.PowerState = PowerStates.On;
            this.labelPower.Text = m_GPS.PowerState.ToString();
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            m_SerialPort.WriteLine(this.labelStart.Text);
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            m_SerialPort.WriteLine(this.labelStop.Text);
        }

        private void buttonClear_Click(object sender, EventArgs e)
        {
            this.textBoxOutput.Text = string.Empty;
        }

        private void buttonReset_Click(object sender, EventArgs e)
        {
            m_GPS.Reset();
        }
    }
}
